package com.cherry.androidviewdemo.widget

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.cherry.androidviewdemo.utils.dp2px

class RippleView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr) {


    private var downX = 0f

    private var downY = 0f

    private var radius = 0f

    private val maxCircleRadius = 30f.dp2px(context)

    private val path = Path()

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)


    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if (radius == 0f) {
            return
        }
        val gradient = RadialGradient(downX, downY, radius, Color.RED, Color.GREEN, Shader.TileMode.CLAMP)
        paint.shader = gradient
        canvas.save()
        path.reset()

        //CW逆时针
        path.addCircle(downX, downY, radius, Path.Direction.CW)

        canvas.drawPath(path, paint)
        canvas.restore()

    }


    override fun onTouchEvent(event: MotionEvent): Boolean {

        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                downX = event.x
                downY = event.y

                val animator = ValueAnimator.ofFloat(0f, maxCircleRadius)
                animator.duration = 3000
                animator.addUpdateListener {
                    radius = it.animatedValue as Float
                    invalidate()
                }

                animator.start()
            }
            MotionEvent.ACTION_MOVE -> {
                downX = event.x
                downY = event.y
                invalidate()
            }
            MotionEvent.ACTION_UP -> {
                val dismissRadius = Math.max(radius, width.toFloat())
                val animator = ValueAnimator.ofFloat(maxCircleRadius, dismissRadius)
                animator.duration = 2000
                animator.addUpdateListener {
                    radius = it.animatedValue as Float
                    if (radius == dismissRadius) {
                        radius = 0f
                    }
                    invalidate()
                }

                animator.start()
            }

        }

        return super.onTouchEvent(event)
    }

}